<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
  <script src="bootstrap.min.js"></script>
  <script type="text/javascript">
    function WebSocketTest() {
      let text = document.getElementById("div_text");
      if ("WebSocket" in window) {
        let ws = new WebSocket("ws://localhost:9999/handler");
        // 建立websocket链接
        ws.onopen = function() {
          let message = "Hello, I am javascript."
          ws.send(message);
          text.innerHTML = "数据发送中...";
        };

        // 通过websocket接收消息
        ws.onmessage = function(evt) {
          let message = evt.data;
          text.innerHTML = "接收到的数据: " + message;
        };

        // 监听websocket关闭事件
        ws.onclose = function() {
          text.innerHTML = "链接已关闭."
          console.log("链接关闭");
        };
      } else {
        alert("浏览器不支持WebSocket!")
      }
    }
  </script>
  <title>websocket client</title>
</head>
<body>
  <div class="col-md-6 m-6 p-2" id="div_ws">
    <a class="btn btn-primary" href="javascript:WebSocketTest()">连接到WebSocket服务器</a>
  </div>
  <div class="col-md-6 border border-primary mx-5 p-2" id="div_text" style="margin:20px;height:100px;">
    display communicate text
  </div>
</body>
</html>